package com.baiyun.controller;

import com.baiyun.common.Constants;
import com.baiyun.common.Result;
import com.baiyun.common.Pass;
import com.baiyun.domain.Role;
import com.baiyun.domain.User;
import com.baiyun.domain.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 查询用户信息
     * @param principal
     * @return
     */
    @GetMapping("/username")
    public Result username(Principal principal){
        User user = userService.getByUsername(principal.getName());
        System.out.println("------------>"+principal.getName());
        List<Role> roles = roleService.getRoleByUserId(user.getId());
        user.setRole(roles);
        return Result.success(user);
    }

    /**
     * 修改用户信息
     * @param userDTO
     * @return
     */
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserDTO userDTO){
        userDTO.setUpdated(new Date());
        if (userService.updateUser(userDTO) == 1){
            return Result.success();
        }else {
            return Result.error(Constants.CODE_600,"系统繁忙，请重试...");
        }
    }

    @PostMapping("/userPass")
    public Result userPass(@Valid @RequestBody Pass pass, Principal principal){
        User user = userService.getByUsername(principal.getName());
        boolean matches = bCryptPasswordEncoder.matches(pass.getCurrentPass(), user.getPassword());
        if (!matches){
            return Result.error(Constants.CODE_400,"旧密码不正确");
        }
        user.setPassword(bCryptPasswordEncoder.encode(pass.getPassword()));
        user.setUpdated(new Date());
        user.setLastLogin(new Date());
        userService.updateById(user);
        return Result.success("修改成功");
    }


}
